package com.iweb.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

//@WebFilter("/*")
public class RuleFilter implements Filter {

    // 可以放行的静态资源
    private List<String> staticResources= Arrays.asList(".png",".jpg",".js",".css","login.jsp");
    // 可以放行的请求
    private List<String> urls = Arrays.asList("/api/admin/login","/api/admin/login/");

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    // 验证是否是静态资源
    private boolean validateStaticResource(String uri){
        for (int i = 0; i < staticResources.size(); i++) {
            if(uri.endsWith(staticResources.get(i))){
                return true;
            }
        }
        return false;
    }

    // 验证请求
    private boolean validateRequest(String uri){
        for (int i = 0; i < urls.size(); i++) {
            if(uri.equals(urls.get(i))){
                return true;
            }
        }
        return false;
    }


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        String uri = req.getRequestURI();
        // 如果是静态资源直接放行
        if(validateStaticResource(uri)){
            chain.doFilter(request,response);
            return; // 终止当前方法
        }
        // 验证放行的请求
        if(validateRequest(uri)){
            chain.doFilter(request,response);
            return;
        }

        // 验证用户是否登录
        // 1. 获取session中的用户
        HttpSession session = req.getSession();
        Object user = session.getAttribute("user");
        // 2. 如果用户存在则放行
        if(user!=null){
            chain.doFilter(request,response);
            return;
        }
        // 3. 不存在则重定向
        resp.sendRedirect("/admin/login.jsp");
    }

    @Override
    public void destroy() {

    }
}
